<?php


namespace app\api\controller\v21;


use app\api\controller\v2\Auth;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZlUserAccountPasswordResetRecord;
use app\common\lib\Aes;
use app\common\lib\Alidayu;
use app\common\lib\Util;
use think\Log;
use think\response\Json;

/**
 * 2.5.0准币控制器
 * Class Coin
 * @package app\api\controller\v21
 */
class Coin extends Auth
{
    /**
     * 准币余额
     * @return Json
     * @throws \Exception
     */
    public function coinNum()
    {
        $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);

        $resData = [
            'coin_num' => (int)($user_coin['balance'] ?? 0),
            'pwd_status' => (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0,
        ];

        return show(config('code.success'), '获取成功', $resData);
    }

    /**
     * 设置支付密码
     */
    public function setPassword()
    {
        $type = input('type/d', 0);
        $oldPassword = trim(input('old_password/s', ''));
        $newPassword = trim(input('new_password/s', ''));
        $aesType = $this->headers['app-type'] === 'harmonyos' ? 'harmonyos' : 'app';

        if (Util::CheckAppVersion('2.7.6') !== '小')
        {
            if ($oldPassword)
            {
                $coinPasswordData = (new Aes())->decryptWithOpenssl($oldPassword, $aesType);
                if ($coinPasswordData)
                {
                    $d = explode(':', $coinPasswordData);
                    $oldPassword = $d ? $d[0] : '';
                } else
                {
                    $oldPassword = '';
                }
            }

            if ($newPassword)
            {
                $coinPasswordData = (new Aes())->decryptWithOpenssl($newPassword, $aesType);
                if ($coinPasswordData)
                {
                    $d = explode(':', $coinPasswordData);
                    $newPassword = $d ? $d[0] : '';
                } else
                {
                    $newPassword = '';
                }
            }
        }

        if (!in_array($type, [1, 2, 3, 4], true) ||
            (in_array($type, [1, 2], true) && strlen($newPassword) !== 6) ||
            (in_array($type, [2, 3, 4], true) && strlen($oldPassword) !== 6))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $data = [
            'type' => $type,
            'old_password' => $oldPassword,
            'new_password' => $newPassword,
        ];

        if (Util::commentCheck($this->user['id'], $data))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $userAccountModel = new ZhunleUserAccount();
        $user_coin = $userAccountModel->getUserCoinFromCache($this->user['id']);
        switch ($type)
        {
            case 1: // 设置支付密码
                if ($user_coin['password'] ?? '')
                {   // 如果设置过密码
                    return show(config('code.error'), '设置失败，密码已经设置过了～');
                }
                $newPassword = md5(md5($newPassword) . $this->user['id']);
                $res = $userAccountModel->UpdateData($this->user['id'], [
                    'password' => $newPassword,
                    'set_password_time' => $this->request->time(),
                ], ['uid' => $this->user['id']]);

                if (!$res)
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }
                break;
            case 2: // 修改支付密码
                if (Util::getAccountResidualErrorNum($this->user['id'], 1) <= 0)
                {
                    return show(config('code.error'), '密码输入错误次数达到上限', ['num' => 0]);
                }

                $oldPassword = md5(md5($oldPassword) . $this->user['id']);
                $user_coin['password'] = $user_coin['password'] ?? '';
                if ($user_coin['password'] !== $oldPassword)
                {   // 旧密码错误
                    $res = Util::getAccountResidualErrorNum($this->user['id'], 2);
                    if ($res > 0)
                    {
                        $msg = "密码输入错误，剩余{$res}次尝试机会";
                    } else
                    {
                        $msg = '密码输入错误次数达到上限';
                    }

                    return show(config('code.error'), $msg, ['num' => $res]);
                }

                $newPassword = md5(md5($newPassword) . $this->user['id']);

                $res = $userAccountModel->UpdateData($this->user['id'], [
                    'password' => $newPassword,
                    'set_password_time' => $this->request->time(),
                ], ['uid' => $this->user['id']]);

                if (!$res)
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }

                break;
            case 3: // 验证旧密码
                if (Util::getAccountResidualErrorNum($this->user['id'], 1) <= 0)
                {
                    return show(config('code.error'), '密码输入错误次数达到上限', ['num' => 0]);
                }

                $oldPassword = md5(md5($oldPassword) . $this->user['id']);
                $user_coin['password'] = $user_coin['password'] ?? '';
                if ($user_coin['password'] !== $oldPassword)
                {   // 旧密码错误
                    $res = Util::getAccountResidualErrorNum($this->user['id'], 2);
                    if ($res > 0)
                    {
                        $msg = "密码输入错误，剩余{$res}次尝试机会";
                    } else
                    {
                        $msg = '密码输入错误次数达到上限';
                    }

                    return show(config('code.error'), $msg, ['num' => $res]);
                } else
                {
                    return show(config('code.success'), '密码正确');
                }
                break;
            case 4://关闭密码
                if (Util::getAccountResidualErrorNum($this->user['id'], 1) <= 0)
                {
                    return show(config('code.error'), '密码输入错误次数达到上限', ['num' => 0]);
                }

                $oldPassword = md5(md5($oldPassword) . $this->user['id']);
                $user_coin['password'] = $user_coin['password'] ?? '';
                if ($user_coin['password'] !== $oldPassword)
                {   // 旧密码错误
                    $res = Util::getAccountResidualErrorNum($this->user['id'], 2);
                    if ($res > 0)
                    {
                        $msg = "密码输入错误，剩余{$res}次尝试机会";
                    } else
                    {
                        $msg = '密码输入错误次数达到上限';
                    }

                    return show(config('code.error'), $msg, ['num' => $res]);
                }

                $res = $userAccountModel->UpdateData($this->user['id'], [
                    'password' => '',
                    'set_password_time' => 0,
                    'update_time' => $this->request->time(),
                ], ['uid' => $this->user['id']]);

                if (!$res)
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }
                break;
        }

        return show(config('code.success'), '设置成功');
    }

    /**
     * 忘记支付密码
     */
    public function resetPassword()
    {
        $idCard = trim(input('id_card/s', ''));
        $name = trim(input('name/s', ''));
        $areaCode = input('area_code/d', 86);
        $tel = trim(input('tel/s', ''));
        $code = input('code/s', '');

        $appConfig = config('app');
        // 短信验证码 或 密码是否存在
        if (empty($code))
        {
            return show(config('code.error'), '请输入验证码');
        }
        if (!$idCard || !$name)
        {
            return show(config('code.error'), '重置失败，身份信息认证失败');
        }

        $userTel = $this->user['tel'] ?: $this->user['temporary_tel'];
        if (($areaCode === 86 ? $tel : $areaCode . '-' . $tel) != $userTel)
        {
            return show(config('code.error'), '重置失败，手机号错误！');
        }

        // 短信登录时，检测验证码是否正确
        if (!empty($code))
        {
            if (!in_array($tel, $appConfig['mobile'])
                || ($areaCode === 86 && $code != substr($appConfig['code'] * (substr($tel, 3, 6)), 0, 6)))
            {
                //苹果和安卓应用商店审核账号，固定验证码为666666
                if (($tel == '13045794520' && $code == '666666')
                    || ($tel == '13261877781' && $code == '666666'))
                {

                } else
                {
                    //  validate 严格校验
                    $mobileCode = Alidayu::getInstance()->checkSmsIdentify($tel, $areaCode);

                    if ($code != $mobileCode)
                    {
                        return show(config('code.error'), '短信验证码错误');
                    }
                }
            }
        }

        $resData = Util::checkIdentityTwoElements($name, $idCard);
        if ($resData['status'] === false)
        {
            return show(config('code.error'), '重置失败，身份信息认证失败');
        }

        try
        {
            $userAccountModel = new ZhunleUserAccount();
            $res = $userAccountModel->UpdateData($this->user['id'], [
                'password' => '',
                'set_password_time' => 0,
            ], ['uid' => $this->user['id']]);
            if ($res)
            {
                // 写入
                (new ZlUserAccountPasswordResetRecord())->save([
                    'uid' => $this->user['id'],
                    'id_card' => $idCard,
                    'name' => $name,
                    'tel' => $areaCode === 86 ? $tel : $areaCode . '-' . $tel, // 国内手机号不拼接国际手机区号
                    'extend' => $resData['extend'], // 存入身份认证结果信息 json_encode数据
                    'create_time' => $this->request->time(),
                ]);
                Util::getAccountResidualErrorNum($this->user['id'], 3);
            }
        }
        catch (\Exception $e)
        {
            Log::write('账号账户支付密码重置失败：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        return show(config('code.success'), '密码重置成功');
    }
}
